package org.hjl.commonutils.exception;

import lombok.extern.slf4j.Slf4j;
import org.hjl.commonutils.result.R;
import org.hjl.commonutils.result.ResultUtil;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 *
 * @author hjl
 * @since 2024-08-05
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理所有业务异常
     *
     * @param e 异常
     * @return Result
     */
    @ExceptionHandler({Exception.class})
    public R<String> systemException(Exception e) {
        log.error(e.getMessage(), e);
        return ResultUtil.error(e.getMessage());
    }

    /**
     * 处理自定义的业务异常
     *
     * @param e 异常
     * @return Result
     */
    @ExceptionHandler({GlobalException.class})
    public R<String> businessException(GlobalException e) {
        log.error(e.getMessage(), e);
        return ResultUtil.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理输入异常 在参数对象中加校验注解 controller方法参数前加@Validated
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> validParamException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        log.error(bindingResult.getFieldError().getDefaultMessage());
        return ResultUtil.error(R.ILLEGAL_CODE, bindingResult.getFieldError().getDefaultMessage());
    }

}
